import { Navigate, useLocation } from 'react-router-dom'

import { CONST_ROUTES } from '@/constants'
import { useMainStore } from '@/store'

const WHITE_LIST: string[] = [
  CONST_ROUTES.INDEX,
  CONST_ROUTES.CATEGORY,
  CONST_ROUTES.SHOP,
  CONST_ROUTES.LOGIN
]

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const { token } = useMainStore()
  const { pathname } = useLocation()

  if (pathname !== CONST_ROUTES.LOGIN) {
    if (!token && !WHITE_LIST.includes(pathname)) {
      return <Navigate to={CONST_ROUTES.LOGIN} replace />
    } else {
      return <>{children}</>
    }
  } else {
    if (token) {
      return <Navigate to={CONST_ROUTES.INDEX} replace />
    } else {
      return <>{children}</>
    }
  }
}
